package com.blb.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLib动态代理实现
 */
public class CGLibFactoryProxy implements MethodInterceptor {

    //被代理对象
    private Object target;

    //创建代理对象
    public Object createProxyInstance(Object target){
        this.target = target;
        //创建增强器
        Enhancer enhancer = new Enhancer();
        //设置父类类型
        enhancer.setSuperclass(target.getClass());
        //设置方法回调
        enhancer.setCallback(this);
        //返回代理对象
        return enhancer.create();
    }

    //调用原有方法，进行增强
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLib代理给产品打广告");
        //调用原有方法
        Object result = method.invoke(target,objects);
        System.out.println("CGLib代理给产品做售后");
        return result;
    }
}
